﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Lists;
using Vouchers;
using AccountingLibs;
using System.Data.SqlClient;
using BasicForms;
using BarcodeLib;
using BasicForms;

namespace BarCode
{
    public partial class FrmBarCode : BasicForms.FrmBase
    {
        const int BARCODE_WIDTH = 190;
        const int BARCODE_HEIGHT = 40;
        public double cPrinterWidth, cPrinterHeight;
        int ColsPerPage, RowsPerPage;
        public void GetValue(ref int SoCot, ref int SoDong,ref double Widths, ref double Hegihts )
        { 
            SoCot=ColsPerPage;
            SoDong=RowsPerPage;
            Widths=cPrinterWidth;
            Hegihts = cPrinterHeight;
        }
        public FrmBarCode()
        {
            InitializeComponent();
        }
        private void FrmMain_Load(object sender, EventArgs e)
        {
            try
            {
                #region cmbDoiTuong
                cmbDoiTuong.DataSource = DanhMucDoiTuongNghiepVu.GetDanhMucNhaCungCap().DataView;
                cmbDoiTuong.DisplayColumn = "Ten";
                cmbDoiTuong.ValueColumn = "ID";
                cmbDoiTuong.AddVisibleColumn("Ma", "Mã");
                cmbDoiTuong.AddVisibleColumn("Ten", "Tên");
                #endregion

                #region cmbNhomHang
                cmbNhomHang.DataSource = DanhMucNhomVatTuHangHoa.GetAll().DataView;
                cmbNhomHang.DisplayColumn = "Ten";
                cmbNhomHang.ValueColumn = "ID";
                cmbNhomHang.AddVisibleColumn("Ma", "Mã");
                cmbNhomHang.AddVisibleColumn("Ten", "Tên");
                #endregion

                CbPaperStyle.SelectedIndex = 1;
                CbDonVi.SelectedIndex = 0;
                for (int i = 0; i < RowsPerPage * ColsPerPage; i++)
                {
                    CbStartAt.Items.Add(i);

                }
                CbStartAt.SelectedIndex = 0;

                numSoLuongIn.Value = 1;
                DgrInHang.ColumnCount = 5;

                if (!RdoTheoPhieuNhap.Checked && !RdoToanBoKhoHang.Checked)
                {
                    txtFindMa.Enabled = false;
                    TxtFindName.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
        private void DgrHangHoa_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                TxtBarCode.Text = DgrHangHoa["Ma", DgrHangHoa.CurrentRow.Index].Value.ToString();
                TxtBookName.Text = DgrHangHoa["Ten", DgrHangHoa.CurrentRow.Index].Value.ToString();
                TxtTopText.Text = DgrHangHoa["Ten", DgrHangHoa.CurrentRow.Index].Value.ToString();
                TxtBottomText.Text = string.Format("{0:0,0}", Decimal.Parse((DgrHangHoa["GiaBia", DgrHangHoa.CurrentRow.Index].Value.ToString())));
                if (RdoToanBoKhoHang.Checked == true)
                {
                    numSoLuongIn.Value = 1;
                }
                else
                {
                    numSoLuongIn.Value = (decimal)DgrHangHoa[3, DgrHangHoa.CurrentRow.Index].Value;
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void RdoToanBoKhoHang_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (RdoToanBoKhoHang.Checked)
                {
                    DanhMucVatTuHangHoa.Instance.DataView.Table.DefaultView.Sort = "Ten";
                    DgrHangHoa.DataSource = Lists.DanhMucVatTuHangHoa.Instance.DataView;
                    TxtFindName.Focus();
                    DgrHangHoa.Columns["Ma"].HeaderText = "Mã";
                    DgrHangHoa.Columns["Ten"].HeaderText = "Tên";
                    DgrHangHoa.Columns["GiaBia"].HeaderText = "Giá bán lẻ";
                    DgrHangHoa.Columns["GiaBia"].DefaultCellStyle.Format = "0";
                    for (int c = 0; c < DgrHangHoa.ColumnCount; c++)
                    {
                        if ((DgrHangHoa.Columns[c].Name == "Ma") || (DgrHangHoa.Columns[c].Name == "Ten") || (DgrHangHoa.Columns[c].Name == "GiaBia"))
                        {
                            DgrHangHoa.Columns[c].Visible = true;
                        }
                        else
                        {
                            DgrHangHoa.Columns[c].Visible = false;
                        }
                    }

                    txtFindMa.Enabled = true;
                    TxtFindName.Enabled = true;
                    cmbDoiTuong.Enabled = true;
                    dtNgayHoaDon.Enabled = false;
                    cmbPhieuNhap.Enabled = false;
                }
                else
                {
                    txtFindMa.Enabled = false;
                    TxtFindName.Enabled = false;
                    cmbDoiTuong.Enabled = false;
                    dtNgayHoaDon.Enabled = true;
                    cmbPhieuNhap.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void RdoTheoPhieuNhap_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (RdoTheoPhieuNhap.Checked)
                    SearhTheoHoaDon();

                FrmProgressBar.StartShowProgress();
                SqlConnection con = new SqlConnection(AccountingLibs.LocalSettings.ConnectString);
                try
                {
                    con.Open();
                    SqlCommand cmd = con.CreateCommand();
                    txtFindMa.Text = "";
                    TxtFindName.Text = "";

                    if (cmbPhieuNhap.SelectedValue != null)
                    {
                        //Hiện hàng theo hóa đơn, nhưng phiếu nhập k in được nên phải sửa

                        //cmd.CommandText = string.Format(
                        //           "SELECT B.Ma, B.Ten, B.GiaBia, A.Value1 AS SoLuong, D.Ten 'TenNCC'\n" +
                        //           "FROM KhoanMucChungTu A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoa1ID = B.ID \n" +
                        //           "    INNER JOIN ChungTu C ON A.ChungTuID = C.ChungTuID \n" +
                        //           "    INNER JOIN DoiTuongNghiepVu D ON D.ID = C.DoiTuongNghiepVu1ID \n" +
                        //           "WHERE A.ChungTuID IN \n" +
                        //           "(  \n" +
                        //           "    SELECT ChungTuID \n" +
                        //           "    FROM ChungTu \n" +
                        //           "    WHERE ChungTuGocID = '{2}' \n" +
                        //           ") \n" +
                        //           "ORDER BY A.ThuTuKhoanMucTrongChungTu",
                        //           txtFindMa.Text, TxtFindName.Text, cmbPhieuNhap.SelectedValue
                        //           );

                        // Hiện hàng phiếu nhập
                        cmd.CommandText = string.Format(
                                   "SELECT B.Ma, B.Ten, B.GiaBia, A.Value1 AS SoLuong, D.Ten 'TenNCC'\n" +
                                   "FROM KhoanMucChungTu A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoa1ID = B.ID \n" +
                                   "    INNER JOIN ChungTu C ON A.ChungTuID = C.ChungTuID \n" +
                                   "    INNER JOIN DoiTuongNghiepVu D ON D.ID = C.DoiTuongNghiepVu1ID \n" +
                                   "WHERE A.ChungTuID = '{2}' \n" +
                                   "ORDER BY A.ThuTuKhoanMucTrongChungTu",
                                   txtFindMa.Text, TxtFindName.Text, cmbPhieuNhap.SelectedValue
                                   );

                        SqlDataAdapter da = new SqlDataAdapter(cmd);
                        DataSet ds = new DataSet();
                        da.Fill(ds);
                        DgrHangHoa.DataSource = ds.Tables[0].DefaultView;
                        DgrHangHoa.Columns["GiaBia"].HeaderText = "Giá bán lẻ";
                        DgrHangHoa.Columns["GiaBia"].DefaultCellStyle.Format = "0";
                        DgrHangHoa.Columns["Ma"].HeaderText = "Mã";
                        DgrHangHoa.Columns["Ten"].HeaderText = "Tên";
                        DgrHangHoa.Columns["SoLuong"].HeaderText = "Số lượng";
                        DgrHangHoa.Columns["SoLuong"].DefaultCellStyle.Format = "0";
                        DgrHangHoa.Columns["TenNCC"].HeaderText = "Tên nhà cung cấp";
                        DgrHangHoa.Columns["TenNCC"].Width = 250;

                        cmd.CommandText = string.Format("SELECT DoiTuongNghiepVu1ID " +
                                                        "FROM ChungTu " +
                                                        "WHERE ChungTuID = '{0}'",
                                                        cmbPhieuNhap.SelectedValue);
                        SqlDataReader dr = cmd.ExecuteReader();
                        if (dr.Read())
                        {
                            cmbDoiTuong.EditValue = (Guid)dr["DoiTuongNghiepVu1ID"];
                        }
                        dr.Close();
                    }
                    DgrHangHoa.DataSource = null;
                }
                catch (Exception ex)
                {
                    BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
                }
                finally
                {
                    con.Close();
                }
                FrmProgressBar.FinishShowProgress();

                txtFindMa.Enabled = true;
                TxtFindName.Enabled = true;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (RdoTheoPhieuNhap.Checked)
                    SearhTheoHoaDon();
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void SearhTheoHoaDon()
        {
            FrmProgressBar.StartShowProgress();
            try
            {
                DieuKienTimKiemChungTu dkTimKiem = new DieuKienTimKiemChungTu();
                DateTime today = dtNgayHoaDon.Value;
                dkTimKiem.TuNgay = new NullableDate(new DateTime(today.Year, today.Month, today.Day, 0, 0, 0));
                dkTimKiem.DenNgay = new NullableDate(new DateTime(today.Year, today.Month, today.Day, 23, 59, 59));
                dkTimKiem.LoaiChungTu = DanhMucLoaiChungTu.Instance.GetByMa("PhieuNhapKho");
                DanhSachChungTu dsHoaDonMua = new DanhSachChungTu();
                dsHoaDonMua.LoadFromDB(dkTimKiem.BuildSqlStatement(1000, 1));
                cmbPhieuNhap.DataSource = dsHoaDonMua.DataTable;
                cmbPhieuNhap.DisplayMember = "So";
                cmbPhieuNhap.ValueMember = "ChungTuID";
            }
            catch (SqlException sqlEx)
            {
                throw new CustomException(CustomException.GetSqlExceptionMessage(sqlEx));
            }
            catch (Exception ex)
            {
                if (ex is CustomException) throw ex;
                else
                {
                    throw new CustomException(ex.Message);
                }
            }
            FrmProgressBar.FinishShowProgress();
        }

        private void CbPaperStyle_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                switch (CbPaperStyle.SelectedIndex)
                {
                    case 0:
                        {
                            cPrinterWidth = 106 * 56.7; //' 106 mm (x 56.7 twip)
                            cPrinterHeight = (73 * 56.7); //'4479 '79 mm
                            break;
                        }
                    case 1:
                        {
                            cPrinterWidth = 6067;//' 107 mm (x 56.7 twip)
                            cPrinterHeight = 5670; //'100 mm
                            break;
                        }
                    case 2:
                        {
                            cPrinterWidth = 5953; //' 105 mm (x 56.7 twip)
                            cPrinterHeight = 8788; //'155 mm
                            break;
                        }
                    case 3:
                        {
                            cPrinterWidth = 11907;//' = 210 mm
                            cPrinterHeight = 16840;// '297 mm
                            break;
                        }
                }
                //CbX.SelectedIndex = Convert.ToInt32(cPrinterWidth / MyBarCode.Width - 1);  
                CbX.SelectedIndex = Convert.ToInt32((int)cPrinterWidth / (int)1815) - 1;
                //CbY.SelectedIndex = Convert.ToInt32(cPrinterHeight / (LbBottom.Top + LbBottom.Height - LbTop.Top) - 1);
                CbY.SelectedIndex = Convert.ToInt32((int)(cPrinterHeight) / (int)(1155)) - 1;
                ColsPerPage = CbX.SelectedIndex + 1;
                RowsPerPage = CbY.SelectedIndex + 1;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void CbY_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                RowsPerPage = CbY.SelectedIndex + 1;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void CbX_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                ColsPerPage = CbX.SelectedIndex + 1;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
       
        private void BtDelete_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (DataGridViewRow r in DgrInHang.SelectedRows)
                {
                    if (r.Index != DgrInHang.RowCount - 1)
                    {
                        DgrInHang.Rows.RemoveAt(r.Index);
                    }
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void DgrInHang_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (DgrInHang.CurrentRow.Index != DgrInHang.RowCount - 1)
                {
                    try
                    {
                        TxtBarCode.Text = DgrInHang[0, DgrInHang.CurrentRow.Index].Value.ToString();
                        TxtBookName.Text = DgrInHang[1, DgrInHang.CurrentRow.Index].Value.ToString();
                        TxtTopText.Text = DgrInHang[1, DgrInHang.CurrentRow.Index].Value.ToString();
                        TxtBottomText.Text = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, DgrInHang.CurrentRow.Index].Value.ToString())));
                        if (numSoLuongIn.Text == "")
                        {
                            numSoLuongIn.Value = 1;
                        }
                        else
                        {
                            try {
                                numSoLuongIn.Value = (int)DgrInHang[3, DgrInHang.CurrentRow.Index].Value;
                            }
                            catch
                            {
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void BtExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            FrmProgressBar.StartShowProgress();
            SqlConnection con = new SqlConnection(AccountingLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                txtFindMa.Text = "";
                TxtFindName.Text = "";
                if (cmbPhieuNhap.SelectedValue is Guid)
                {
                    cmd.CommandText = string.Format(
                               "SELECT B.Ma, B.Ten, B.GiaBia, A.Value1 AS SoLuong, D.Ten 'TenNCC'\n" +
                               "FROM KhoanMucChungTu A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoa1ID = B.ID \n" +
                               "    INNER JOIN ChungTu C ON A.ChungTuID = C.ChungTuID \n" +
                               "    INNER JOIN DoiTuongNghiepVu D ON D.ID = C.DoiTuongNghiepVu1ID \n" +
                               "WHERE A.ChungTuID = '{2}' \n" +
                               "ORDER BY A.ThuTuKhoanMucTrongChungTu",
                               txtFindMa.Text, TxtFindName.Text, cmbPhieuNhap.SelectedValue
                               );

                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    da.Fill(ds);
                    DgrHangHoa.DataSource = ds.Tables[0].DefaultView;
                    DgrHangHoa.Columns["GiaBia"].HeaderText = "Giá bán lẻ";
                    DgrHangHoa.Columns["GiaBia"].DefaultCellStyle.Format = "0";
                    DgrHangHoa.Columns["Ma"].HeaderText = "Mã";
                    DgrHangHoa.Columns["Ten"].HeaderText = "Tên";
                    DgrHangHoa.Columns["SoLuong"].HeaderText = "Số lượng";
                    DgrHangHoa.Columns["SoLuong"].DefaultCellStyle.Format = "0";
                    DgrHangHoa.Columns["TenNCC"].HeaderText = "Tên nhà cung cấp";

                    DgrHangHoa.Columns["GiaBia"].Width = 80;
                    DgrHangHoa.Columns["Ten"].Width = 200;
                    DgrHangHoa.Columns["SoLuong"].Width = 60;
                    DgrHangHoa.Columns["TenNCC"].Width = 250;

                    cmd.CommandText = string.Format("SELECT DoiTuongNghiepVu1ID " +
                                                    "FROM ChungTu " +
                                                    "WHERE ChungTuID = '{0}'",
                                                    cmbPhieuNhap.SelectedValue);
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.Read())
                    {
                        cmbDoiTuong.EditValue = (Guid)dr["DoiTuongNghiepVu1ID"];
                    }
                    dr.Close();
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
            }
            FrmProgressBar.FinishShowProgress();
        }

        private void BtEdit_Click(object sender, EventArgs e)
        {
            DgrInHang[3, DgrInHang.CurrentRow.Index].Value = numSoLuongIn.Value;
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        private void TxtFindName_TextChanged(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(AccountingLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();

                if (RdoTheoPhieuNhap.Checked)
                {
                    cmd.CommandText = string.Format(
                           "SELECT B.Ma, B.Ten, B.GiaBia, A.Value1 AS SoLuong, D.Ten 'TenNCC'\n" +
                           "FROM KhoanMucChungTu A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoa1ID = B.ID \n" +
                           "    INNER JOIN ChungTu C ON A.ChungTuID = C.ChungTuID \n" +
                           "    INNER JOIN DoiTuongNghiepVu D ON D.ID = C.DoiTuongNghiepVu1ID \n" +
                           "WHERE B.Ma like N'%{0}%' AND B.Ten like N'%{1}%' AND A.ChungTuID IN \n" +
                           "(  \n" +
                           "    SELECT ChungTuID \n" +
                           "    FROM ChungTu \n" +
                           "    WHERE ChungTuGocID = '{2}' \n" +
                           ") \n" +
                           "ORDER BY A.ThuTuKhoanMucTrongChungTu",
                           txtFindMa.Text, TxtFindName.Text, cmbPhieuNhap.SelectedValue
                           );
                }
                else
                {
                    cmd.CommandText = string.Format(
                                "SELECT Ma, Ten, GiaBia                     \n" +
                                "FROM VatTuHangHoa                          \n" +
                                "WHERE Ma like N'%{0}%' AND Ten like N'%{1}%'   \n",
                                txtFindMa.Text, TxtFindName.Text
                                );
                }
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();

                da.Fill(ds);
                DgrHangHoa.DataSource = ds.Tables[0].DefaultView;
                DgrHangHoa.Columns["GiaBia"].HeaderText = "Giá bán lẻ";
                DgrHangHoa.Columns["GiaBia"].DefaultCellStyle.Format = "0";
                DgrHangHoa.Columns["Ma"].HeaderText = "Mã";
                DgrHangHoa.Columns["Ten"].HeaderText = "Tên";
                if (RdoTheoPhieuNhap.Checked)
                {
                    DgrHangHoa.Columns["TenNCC"].HeaderText = "Tên nhà cung cấp";
                    DgrHangHoa.Columns["TenNCC"].Width = 250;
                }
                DgrHangHoa.Columns["GiaBia"].Width = 80;
                DgrHangHoa.Columns["Ten"].Width = 200;
                //DgrHangHoa.Columns["SoLuong"].Width = 60;
                
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
            }
        }

        private void txtFindMa_TextChanged(object sender, EventArgs e)
        {
            try
            {
                SqlConnection con = new SqlConnection(AccountingLibs.LocalSettings.ConnectString);
                try
                {
                    con.Open();
                    SqlCommand cmd = con.CreateCommand();

                    if (RdoTheoPhieuNhap.Checked)
                    {
                        cmd.CommandText = string.Format(
                               "SELECT B.Ma, B.Ten, B.GiaBia, A.Value1 AS SoLuong, D.Ten 'TenNCC'\n" +
                               "FROM KhoanMucChungTu A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoa1ID = B.ID \n" +
                               "    INNER JOIN ChungTu C ON A.ChungTuID = C.ChungTuID \n" +
                               "    INNER JOIN DoiTuongNghiepVu D ON D.ID = C.DoiTuongNghiepVu1ID \n" +
                               "WHERE B.Ma like N'%{0}%' AND B.Ten like N'%{1}%' AND A.ChungTuID IN \n" +
                               "(  \n" +
                               "    SELECT ChungTuID \n" +
                               "    FROM ChungTu \n" +
                               "    WHERE ChungTuGocID = '{2}' \n" +
                               ") \n" +
                               "    ORDER BY A.ThuTuKhoanMucTrongChungTu",
                               txtFindMa.Text, TxtFindName.Text, cmbPhieuNhap.SelectedValue
                               );
                    }
                    else
                    {
                        cmd.CommandText = string.Format(
                                    "SELECT Ma, Ten, GiaBia                     \n" +
                                    "FROM VatTuHangHoa                          \n" +
                                    "WHERE Ma like N'%{0}%' AND Ten like N'%{1}%'   \n",
                                    txtFindMa.Text, TxtFindName.Text
                                    );
                    }
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataSet ds = new DataSet();

                    da.Fill(ds);
                    DgrHangHoa.DataSource = ds.Tables[0].DefaultView;
                    DgrHangHoa.Columns["GiaBia"].HeaderText = "Giá bán lẻ";
                    DgrHangHoa.Columns["GiaBia"].DefaultCellStyle.Format = "0";
                    DgrHangHoa.Columns["Ma"].HeaderText = "Mã";
                    DgrHangHoa.Columns["Ten"].HeaderText = "Tên";
                    if (RdoTheoPhieuNhap.Checked)
                    {
                        DgrHangHoa.Columns["TenNCC"].HeaderText = "Tên nhà cung cấp";
                        DgrHangHoa.Columns["TenNCC"].Width = 250;
                    }
                    DgrHangHoa.Columns["GiaBia"].Width = 80;
                    DgrHangHoa.Columns["Ten"].Width = 200;
                    //DgrHangHoa.Columns["SoLuong"].Width = 60;
                }
                catch (Exception ex)
                {
                    BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
                }
                finally
                {
                    con.Close();
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void DgrHangHoa_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (cmbDoiTuong.EditValue == null)
                {
                    MessageBox.Show("Bạn chưa chọn nhà cung cấp mặt hàng");
                    cmbDoiTuong.Focus();
                }
                else
                {
                    if (RdoTheoPhieuNhap.Checked)
                    {
                        foreach (DataGridViewRow r in DgrHangHoa.SelectedRows)
                        {
                            DgrInHang.Rows.Add(DgrHangHoa["Ma", r.Index].Value, DgrHangHoa["Ten", r.Index].Value, DgrHangHoa["GiaBia", r.Index].Value, DgrHangHoa["SoLuong", r.Index].Value,
                                                DanhMucDoiTuongNghiepVu.Instance.GetByID((Guid)cmbDoiTuong.EditValue).Ma);
                        }
                    }
                    else
                    {
                        foreach (DataGridViewRow r in DgrHangHoa.SelectedRows)
                        {
                            DgrInHang.Rows.Add(DgrHangHoa["Ma", r.Index].Value, DgrHangHoa["Ten", r.Index].Value, DgrHangHoa["GiaBia", r.Index].Value, numSoLuongIn.Value,
                                                DanhMucDoiTuongNghiepVu.Instance.GetByID((Guid)cmbDoiTuong.EditValue).Ma);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                //DgrInHang.ColumnCount = 5;
                if (cmbDoiTuong.EditValue == null)
                {
                    MessageBox.Show("Bạn chưa chọn nhà cung cấp mặt hàng");
                    cmbDoiTuong.Focus();
                }
                else
                {
                    int count = DgrHangHoa.SelectedRows.Count;
                    if (RdoTheoPhieuNhap.Checked)
                    {
                        
                        for (int i = count-1; i >=0; i--)
                        {
                            //convert decimal -> int de hien cho chuan
                            int giaBia = Convert.ToInt32(DgrHangHoa["GiaBia", DgrHangHoa.SelectedRows[i].Index].Value);
                            int soLuong = Convert.ToInt32(DgrHangHoa["SoLuong", DgrHangHoa.SelectedRows[i].Index].Value);
                            DgrInHang.Rows.Add(DgrHangHoa["Ma", DgrHangHoa.SelectedRows[i].Index].Value, DgrHangHoa["Ten", DgrHangHoa.SelectedRows[i].Index].Value, giaBia, soLuong,//DgrHangHoa["GiaBia", DgrHangHoa.SelectedRows[i].Index].Value, DgrHangHoa["SoLuong", DgrHangHoa.SelectedRows[i].Index].Value,
                                                      DanhMucDoiTuongNghiepVu.Instance.GetByID((Guid)cmbDoiTuong.EditValue).Ma);
                        }
                    }
                    else
                    {
                        for (int i = count-1; i >= 0; i--)
                        {
                            int giaBia = Convert.ToInt32(DgrHangHoa["GiaBia", DgrHangHoa.SelectedRows[i].Index].Value);
                            int soLuong = Convert.ToInt32(numSoLuongIn.Value);
                            DgrInHang.Rows.Add(DgrHangHoa["Ma", DgrHangHoa.SelectedRows[i].Index].Value, DgrHangHoa["Ten", DgrHangHoa.SelectedRows[i].Index].Value, giaBia, soLuong,//DgrHangHoa["GiaBia", DgrHangHoa.SelectedRows[i].Index].Value, numSoLuongIn.Value,
                                            DanhMucDoiTuongNghiepVu.Instance.GetByID((Guid)cmbDoiTuong.EditValue).Ma);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void PrintA4()
        {
            try
            {
                if (DgrInHang.RowCount == 0)
                {
                    MessageBox.Show("Bạn chưa chọn mặt hàng để in mã vạch");
                }
                else
                {
                    DsPrintBarCode ds = new DsPrintBarCode();
                    DataRow row = null;

                    int index = 0;

                    for (int r = 0; r < DgrInHang.RowCount - 1; r++)//moi loai tem
                    {
                        int soLuong = Convert.ToInt32(DgrInHang[3, r].Value);
                        string strTen = (DgrInHang[1, r].Value).ToString();
                        if (strTen.Length > 22)
                        {
                            strTen = strTen.Substring(0, 19) + "...";
                        }

                        for (int c = 0; c < soLuong; c++)//moi tem cua mot loai
                        {
                            if (index == 0)
                            {
                                row = ds.DataTable1.NewRow();
                                ds.DataTable1.Rows.Add(row);
                            }
                            index++;

                            System.IO.MemoryStream ms = new System.IO.MemoryStream();
                            Image image = GenBarCodeImage((string)(DgrInHang[0, r].Value), BARCODE_WIDTH+10, BARCODE_HEIGHT);
                            if (image != null) image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

                            switch (index)
                            {
                                case 1:
                                    row["Image1"] = ms.ToArray();
                                    row["Ten1"] = strTen;
                                    row["Gia1"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai1"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 2:
                                    row["Image2"] = ms.ToArray();
                                    row["Ten2"] = strTen;
                                    row["Gia2"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai2"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;

                                case 3:
                                    row["Image3"] = ms.ToArray();
                                    row["Ten3"] = strTen;
                                    row["Gia3"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai3"] = ((DgrInHang[4, r].Value.ToString()));
                                    //index = 0;
                                    break;
                                case 4:

                                    row["Image4"] = ms.ToArray();
                                    row["Ten4"] = strTen;
                                    row["Gia4"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai4"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 5:
                                    row["Image5"] = ms.ToArray();
                                    row["Ten5"] = strTen;
                                    row["Gia5"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai5"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;

                                case 6:
                                    row["Image6"] = ms.ToArray();
                                    row["Ten6"] = strTen;
                                    row["Gia6"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai6"] = ((DgrInHang[4, r].Value.ToString()));
                                    index = 0;
                                    break;
                            }
                        }
                    }


                    RptA4Barcode report = new RptA4Barcode();
                    report.SetDataSource(ds);

                    FrmShowReport frm = new FrmShowReport();
                    frm.crystalReportViewer1.ReportSource = report;
                    frm.Show();
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
     
        private void PrintThreeColumnBarCode()
        {
            try
            {
                if (DgrInHang.RowCount == 0)
                {
                    MessageBox.Show("Bạn chưa chọn mặt hàng để in mã vạch");
                }
                else
                {
                    DsPrintBarCode ds = new DsPrintBarCode();
                    DataRow row = null;

                    int index = 0;

                    for (int r = 0; r < DgrInHang.RowCount - 1; r++)//moi loai tem
                    {
                        int soLuong = Convert.ToInt32(DgrInHang[3, r].Value);
                        string strTen = (DgrInHang[1, r].Value).ToString();
                        if (strTen.Length > 22)
                        {
                            strTen = strTen.Substring(0, 19) + "...";
                        }

                        for (int c = 0; c < soLuong; c++)//moi tem cua mot loai
                        {
                            if (index == 0)
                            {
                                row = ds.DataTable1.NewRow();
                                ds.DataTable1.Rows.Add(row);
                            }
                            index++;

                            System.IO.MemoryStream ms = new System.IO.MemoryStream();
                            Image image = GenBarCodeImage((string)(DgrInHang[0, r].Value), BARCODE_WIDTH, BARCODE_HEIGHT);
                            if (image != null) image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

                            switch (index)
                            {
                                case 1:
                                    row["Image1"] = ms.ToArray();
                                    row["Ten1"] = strTen;
                                    row["Gia1"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai1"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 2:
                                    row["Image2"] = ms.ToArray();
                                    row["Ten2"] = strTen;
                                    row["Gia2"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai2"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 3:
                                    row["Image3"] = ms.ToArray();
                                    row["Ten3"] = strTen;
                                    row["Gia3"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai3"] = ((DgrInHang[4, r].Value.ToString()));
                                    index = 0;
                                    break;
                            }
                        }
                    }

                    CrystalDecisions.CrystalReports.Engine.ReportClass report = null;
                    report = new RptBarcodeCTSHN();
                    report.SetDataSource(ds);

                    FrmShowReport frm = new FrmShowReport();
                    frm.crystalReportViewer1.ReportSource = report;
                    frm.Show();
                }
            }
            catch (SqlException sqlEx)
            {
                throw new CustomException(CustomException.GetSqlExceptionMessage(sqlEx));
            }
            catch (Exception ex)
            {
                if (ex is CustomException) throw ex;
                else
                {
                    throw new CustomException(ex.Message);
                }
            }
        
        }
        private Image GenBarCodeImage(string ma, int width, int height)
        {
            try
            {
                BarcodeLib.Barcode barcode = new BarcodeLib.Barcode();
                barcode.Alignment = AlignmentPositions.CENTER;
                barcode.IncludeLabel = true;
                Image image = barcode.Encode(TYPE.EAN13, ma, Color.Black, Color.White, width, height);
                return image;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        // in chuyên dụng
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                 PrintThreeColumnBarCode();
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
        // in A4
        private void BtPrint_Click(object sender, EventArgs e)
        {
            try
            {
                PrintA4();
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void cmbNhomHang_EditValueChanged(object sender, EventArgs e)
        {
            FrmProgressBar.StartShowProgress();
            SqlConnection con = new SqlConnection(AccountingLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                txtFindMa.Text = "";
                TxtFindName.Text = "";
                RdoTheoPhieuNhap.Checked = false;
                RdoToanBoKhoHang.Checked = true;

                cmd.CommandText = string.Format("SELECT * FROM VatTuHangHoa WHERE NhomVatTuHangHoaID = '{0}'", cmbNhomHang.EditValue.ToString());

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                DgrHangHoa.DataSource = ds.Tables[0].DefaultView;
                DgrHangHoa.Columns["GiaBia"].HeaderText = "Giá bán lẻ";
                DgrHangHoa.Columns["GiaBia"].DefaultCellStyle.Format = "0";
                DgrHangHoa.Columns["Ma"].HeaderText = "Mã";
                DgrHangHoa.Columns["Ten"].HeaderText = "Tên";
                DgrHangHoa.Columns["GiaBia"].Width = 80;
                DgrHangHoa.Columns["Ten"].Width = 200;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
            }
            FrmProgressBar.FinishShowProgress();
        }
    }
}

